﻿// ===============================================================================
// DotNet.Platform 开发框架 2016 版权所有
// ===============================================================================

using System;
using System.Web;
using System.Web.Mvc;

namespace XNWebAPI
{
    public class JsonStringResult : JsonResult
    {
        private string JsonString { get; set; }

        /// <summary>
        /// 初始化 JsonStringResult 类的新实例。
        /// </summary>
        public JsonStringResult()
        {
            this.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
        }

        /// <summary>
        /// 初始化 JsonStringResult 类的新实例。
        /// </summary>
        /// <param name="jsonString">字符串</param>
        public JsonStringResult(string jsonString) : this()
        {
            this.JsonString = jsonString;
        }


        /// <summary>
        /// 通过从 <see cref="T:System.Web.Mvc.ActionResult"/> 类继承的自定义类型，启用对操作方法结果的处理。
        /// </summary>
        /// <param name="context">执行结果时所处的上下文。</param><exception cref="T:System.ArgumentNullException"><paramref name="context"/> 参数为 null。</exception>
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");
            if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
                throw new InvalidOperationException("此请求已被阻止，因为当用在 GET 请求中时，会将敏感信息透漏给第三方网站。若要允许 GET 请求，请将 JsonRequestBehavior 设置为 AllowGet。");

            HttpResponseBase response = context.HttpContext.Response;
            response.ContentType = "application/json";

            if (this.ContentEncoding != null)
                response.ContentEncoding = this.ContentEncoding;
            response.Write(JsonString);
        }
    }
}